package com.zby.business.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.zby.business.R;
import com.zby.business.net.MyAsyncTask;
import com.zby.business.util.App;
import com.zby.business.util.Util;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * Created by BY on 2016/3/14.
 */
public class MySalePage extends Activity {
    private RelativeLayout layout;
    private Button saleButton;
    private ListView listView;
    private App app;
    private ArrayList detailId, orderId, detailIntroduce, detailPicture, name, phone, number, price, address;
    private MySaleAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.mysale);
        initView();
        initData();
        super.onCreate(savedInstanceState);
    }

    private void initData() {
        MyAsyncTask task = new MyAsyncTask();
        try {
            String s = task.execute("getOrder?userId=" + app.getUserId() + "&status=0").get();
            System.out.println(s);
            JSONObject json = new JSONObject(s);
            JSONArray details = json.getJSONArray("detail");
            JSONArray users = json.getJSONArray("userDetails");
            JSONArray orders = json.getJSONArray("order");
            for (int i = 0; i < details.length(); i++) {
                JSONObject detail = (JSONObject) details.get(i);
                JSONObject user = (JSONObject) users.get(i);
                JSONObject order = (JSONObject) orders.get(i);
                number.add(order.get("number"));
                price.add(order.get("price"));
                detailPicture.add(detail.get("commodityPicture"));
                detailIntroduce.add(detail.get("commodityBrand"));
                detailId.add(detail.get("commodityDetailId"));
                orderId.add(order.get("orderid"));
                name.add(user.get("name"));
                phone.add(user.get("phone"));
                address.add(user.get("address"));
            }
            adapter = new MySaleAdapter();
            listView.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        orderId.clear();
        detailIntroduce.clear();
        detailId.clear();
        detailPicture.clear();
        name.clear();
        phone.clear();
        number.clear();
        address.clear();
        price.clear();
        initData();
        super.onResume();
    }

    private void initView() {
        detailId = new ArrayList();
        detailIntroduce = new ArrayList();
        detailPicture = new ArrayList();
        orderId = new ArrayList();
        name = new ArrayList();
        phone = new ArrayList();
        number = new ArrayList();
        price = new ArrayList();
        address = new ArrayList();
        app = (App) getApplication();
        layout = (RelativeLayout) findViewById(R.id.backLayout);
        saleButton = (Button) findViewById(R.id.myPageButton);
        listView = (ListView) findViewById(R.id.myPageListView);
        saleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), UpLoad.class));
            }
        });
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    class MySaleAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private Button send, modify;
        private ImageView image;
        private ImageLoader imageLoader;
        private LruCache cache;
        private TextView introduce, userinfo, count;

        public MySaleAdapter() {
            imageLoader = ImageLoader.getInstance();
            ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(getApplicationContext());
            imageLoader.init(config);
            cache = new LruCache((int) (Runtime.getRuntime().maxMemory() / 20));
            inflater = LayoutInflater.from(getApplicationContext());
        }

        @Override
        public int getCount() {
            return detailId.size();
        }

        @Override
        public Object getItem(int position) {
            return detailId.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.my_sale_list_item, null);
            send = (Button) convertView.findViewById(R.id.mySaleDeleteButton);
//            modify = (Button) convertView.findViewById(R.id.mySaleModifyButton);
            introduce = (TextView) convertView.findViewById(R.id.mySaleIntroduceTextView);
            userinfo = (TextView) convertView.findViewById(R.id.userInfo);
            count = (TextView) convertView.findViewById(R.id.count);
            image = (ImageView) convertView.findViewById(R.id.mySaleListViewImage);
            introduce.setText(detailIntroduce.get(position) + "");
            userinfo.setText(name.get(position) + "  " + phone.get(position) + "  " + address.get(position));
            count.setText(price.get(position) + "  *" + number.get(position));
            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyAsyncTask asyncTask = new MyAsyncTask();
                    try {
                        String s = asyncTask.execute("changeStatus?orderId=" + orderId.get(position) + "&status=0&userId=" + app.getUserId()).get();
                        System.out.println(s);
                        detailId.remove(position);
                        orderId.remove(position);
                        detailIntroduce.remove(position);
                        name.remove(position);
                        phone.remove(position);
                        number.remove(position);
                        price.remove(position);
                        adapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            final String[] urls = detailPicture.get(position).toString().split("\\;");
            Bitmap bitmap = (Bitmap) cache.get(urls[0]);
            if (bitmap != null) {
                image.setImageBitmap(bitmap);
            } else {
                imageLoader.displayImage(Util.BASE_URL + urls[0], image);
                imageLoader.loadImage(Util.BASE_URL + urls[0], new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String s, View view) {

                    }

                    @Override
                    public void onLoadingFailed(String s, View view, FailReason failReason) {

                    }

                    @Override
                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                        cache.put(urls[0], bitmap);
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view) {

                    }
                });
            }
            return convertView;
        }
    }
}
